<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true">
      <el-form-item label="商户" v-if="rolesKey == '00'">
        <el-select
          v-model="queryParams.shopId"
          filterable
          remote
          reserve-keyword
          placeholder="请输入搜索商户并选择"
          :remote-method="remoteMethod"
          :loading="loading">
          <el-option
            v-for="item in merchantList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="优惠券标题" prop="roleName">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入优惠券标题"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="优惠券状态"
          clearable
          size="small"
          style="width: 240px"
        >
          <el-option
            v-for="dict in couponStatus"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="有效时间">
        <el-date-picker
          v-model="dateRangeFilter"
          size="small"
          type="datetimerange"
          style="width: 240px"
          value-format="yyyy-MM-dd HH:mm:ss"
          range-separator="-"
          @change="pickerChangeFilter"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-if="rolesKey == '00'"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="openMerchant"
          v-hasPermi="['shop:coupon:add']"
        >新增
        </el-button>
        <el-button
          v-else
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['shop:coupon:add']"
        >新增
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['shop:coupon:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['shop:coupon:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="roleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>

      <el-table-column label="商户名称" align="center" prop="shopName" />
      <el-table-column label="优惠券标题" align="center" prop="title" />
      <el-table-column label="封面"
                       align="center"
                       key="coverImg"
                       width="150"
                       :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-image :src="scope.row.coverImg"
                    style="width: 100px; height: 100px"
                    fit="cover"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column label="优惠券类型" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.type == 0">代金券</span>
          <span v-if="scope.row.type == 1">折扣券</span>
          <span v-if="scope.row.type == 2">兑换券</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="折扣" align="center" prop="discount" />
      <el-table-column label="满减金额" prop="amount" /> -->

      <el-table-column label="剩余数量(张)" align="center" prop="quantity" >
        <template slot-scope="scope">
          <span>{{scope.row.quantity == 99999999 ? '有效期内不限量' : scope.row.quantity}}</span>

        </template>

      </el-table-column>

      <el-table-column label="优惠券状态" align="center" >
        <template slot-scope="scope">
          <span style="color: #ffb19a" v-if="scope.row.status == 0">待上架</span>
          <span style="color: #5bd94c" v-if="scope.row.status == 1">已上架</span>
          <span style="color: #ff0000;" v-if="scope.row.status == 2">已过期</span>
          <span style="color: #ff0000;" v-if="scope.row.status == 3">已下架</span>
        </template>
      </el-table-column>
      <el-table-column label="当前绑定的活动" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.isRelevancy == 0">无</span>
          <span v-if="scope.row.isRelevancy == 1">{{scope.row.activityName}}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="用户领券上限" align="center" prop="collectionTimes" /> -->
      <el-table-column label="时间限制" align="center" prop="timeType">
        <template slot-scope="scope">
          <div v-if="scope.row.timeType == 0">领取后{{scope.row.days}}天内 <br><p style="color: red; font-size: 5px">{{scope.row.timeRemaining}}</p></div>
          <div v-if="scope.row.timeType == 1"><div>{{scope.row.startTime}}</div>至<div>{{scope.row.endTime}}</div></div>
        </template>
      </el-table-column>
      <!-- <el-table-column label="使用须知" align="center" prop="useNotice" /> -->
      <!-- <el-table-column label="最低消费" align="center" prop="minCost" >
        <template slot-scope="scope">
          <span>{{scope.row.minCost == 0 ? '无限' : scope.row.minCost}}</span>
        </template>
      </el-table-column> -->

      <el-table-column  label="是否上架" align="center" width="150">
        <template slot-scope="scope">
          <el-switch
            :disabled="scope.row.status == 2"
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            active-text="上架"
            inactive-text="下架"
            @change="changePutStatus($event,scope.row)"
            active-color="#3894ff"
            v-has-permi="['shop:coupon:edit']"
            inactive-color="#ed5565">
          </el-switch>
        </template>

      </el-table-column>
      <!-- <el-table-column label="封面介绍" align="center" prop="coverInfo" /> -->

      <!-- <el-table-column label="有效期开始时间" align="center" prop="startTime" >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="有效期结束时间" align="center" prop="endTime" >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime) }}</span>
        </template>
      </el-table-column> -->

      <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
        <template slot-scope="scope" >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleGet(scope.row)"
            v-hasPermi="['system:couponDraw:list']"
            >查询领券列表
          </el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-has-permi="['shop:coupon:edit']"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>

          <el-button
            size="mini"
            type="text"
            @click="getDetail(scope.row)"
            v-hasPermi="['shop:coupon:query']"
          >查看优惠券详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
<!--    商户列表-->
    <el-dialog title="选择商户" :visible.sync="merchantOpen" width="1400px" append-to-body>
      <el-row >
        <el-col :span="24" :xs="24">
          <el-form :model="queryMerchant" ref="queryMerchantForm" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="商户名称" >
              <el-input
                v-model="queryMerchant.name"
                placeholder="请输入商户名称"
                clearable
                size="small"
                style="width: 240px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="商户手机号码" label-width="100px" prop="phone">
              <el-input
                v-model="queryMerchant.phone"
                placeholder="请输入商户手机号码"
                clearable
                size="small"
                style="width: 240px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="商户状态" prop="status">
              <el-select
                v-model="queryMerchant.status"
                placeholder="商户状态"
                clearable
                size="small"
                style="width: 240px"
              >
                <el-option
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="getMerchantList">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetMerchantQuery">重置</el-button>
            </el-form-item>
          </el-form>
          <el-table v-loading="loading" :data="merchantList">
            <el-table-column label="商家头像" align="center" key="pic" width="150px"  :show-overflow-tooltip="true" >
              <template slot-scope="scope">
                <el-image :src="scope.row.pic"
                          style="width: 100px; height: 100px"
                          fit="cover"
                ></el-image>
              </template>
            </el-table-column>
            <!-- <el-table-column label="商家ID" align="center" key="id" prop="id"  :show-overflow-tooltip="true" /> -->
            <el-table-column label="商家名称" align="center" key="name" prop="name" :show-overflow-tooltip="true" />
            <el-table-column label="负责人" align="center" key="leader	" prop="leader"  :show-overflow-tooltip="true" />
            <el-table-column label="代理商名称	" align="center" key="proxyName" prop="proxyName"  />
            <!-- <el-table-column label="代理商手机号码	" align="center" key="phone" prop="phone"   />
            <el-table-column label="营业时间" align="center" key="businessTime" prop="businessTime" :show-overflow-tooltip="true" />
            <el-table-column label="商户邮箱" align="center" key="email" prop="email" :show-overflow-tooltip="true" />
            <el-table-column label="热度" align="center" key="heat" prop="heat" :show-overflow-tooltip="true" />
            <el-table-column label="商户余额	" align="center" key="videoCount" prop="videoCount"   /> -->
            <el-table-column label="商户状态" align="center" key="status" >
              <template slot-scope="scope">
                <span style="color: #3894ff" v-if="scope.row.status == 0">正常</span>
                <span style="color: #ed5565" v-if="scope.row.status == 1">停用</span>
              </template>
            </el-table-column>
            <!-- <el-table-column label="创建时间" align="center" prop="createTime" width="160">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column> -->
            <el-table-column
              fixed="right"
              label="操作"
              align="center"
              width="100px"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope" >
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-add"
                  @click="handleAdd(scope.row)"
                  v-hasPermi="['system:user:edit']"
                >添加优惠券</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryMerchant.pageNum"
            :limit.sync="queryMerchant.pageSize"
            @pagination="getList"
          />
        </el-col>
      </el-row>
    </el-dialog>
    <!-- 添加或修改优惠券配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules"  label-width="120px">
        <el-row>
          <el-col :span="20">
            <el-form-item label="优惠券标题" prop="title">
              <el-input v-model="form.title" maxlength="50"
                        show-word-limit/>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="发放数量" prop="quantity" type="quantity" >
              <el-input-number v-model="form.quantity" :step="1" :min="10" :max="99999" step-strictly controls-position="right"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="用户领券上限" prop="collectionTimes">
              <el-input-number v-model="form.collectionTimes" :step="1" :min="1" :max="100" step-strictly controls-position="right"/>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="优惠券状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in couponStatus"
                          :key="dict.dictValue"
                          :label="dict.dictValue"
                          :disabled="dict.disabled"
                          >{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="商品类型" prop="type">
              <el-radio-group v-model="form.goodsType">
                <el-radio v-for="dict in couponGoodsType"
                          :key="dict.dictValue"
                          :label="dict.dictValue">{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="优惠券类型" prop="type">
              <el-radio-group v-model="form.type">
                <el-radio v-for="dict in couponType"
                          :key="dict.dictValue"
                          :label="dict.dictValue"
                >{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="最低消费" prop="minCost">
              <el-input v-model="form.minCost"/>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="form.type == 0">
            <el-form-item label="减免金额" prop="amount">
              <el-input v-model="form.amount"/>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="form.type == 1">
            <el-form-item label="折扣" prop="discount">
              <el-input v-model="form.discount"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="时间类型" prop="type">
              <el-radio-group v-model="form.timeType" >
                <el-radio v-for="dict in couponTimeType"
                          :key="dict.dictValue"
                          :label="dict.dictValue"
                          @change="timeChange"
                >{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="form.timeType == 0">
            <el-form-item label="优惠券有效天数" >
              <!-- <el-input v-model="form.days"/> -->
              <el-input-number v-model="form.days" controls-position="right" :min="1"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="form.timeType == 1">
            <el-form-item label="优惠券有效范围" >
              <el-date-picker
                v-model="timeValue"
                type="datetimerange"
                :picker-options="pickerOptions"
                range-separator="至"
                value-format="yyyy-MM-dd HH:mm:ss"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="pickerChange"
                align="right">
              </el-date-picker>
            </el-form-item>

          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20">
            <el-form-item label="使用须知" prop="useNotice">
              <el-input type="textarea" :rows="3" v-model="form.useNotice" maxlength="255"
                        show-word-limit/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="封面">
          <upload :value="form.coverImg" :limit="1" @uploadSuccess="uploadSuccess"></upload>
        </el-form-item>
        <!-- <el-form-item label="封面介绍" >
          <el-input type="textarea" v-model="form.coverInfo"></el-input>
        </el-form-item> -->
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 领取优惠券列表弹出框 -->
    <el-dialog title="用户领取优惠券列表"  :visible.sync="openlist"  append-to-body>
        <el-table ref="table" :data="couponTable">
            <el-table-column label="抖音用户名称" prop="userName"/>
            <el-table-column label="活动标题" prop="activityName"/>
            <el-table-column label="优惠券标题" prop="couponName"/>
            <el-table-column label="获取途径" prop="getType">
              <template slot-scope="scope">
                <span v-if="scope.row.getType == 0">抖音</span>
                <span v-if="scope.row.getType == 1">快手</span>

              </template>
            </el-table-column>
            <el-table-column label="使用状态" prop="useStatus">
              <template slot-scope="scope">
                <span v-if="scope.row.useStatus == 0">未使用</span>
                <span v-if="scope.row.useStatus == 1">已使用</span>
                <span v-if="scope.row.useStatus == 2">已过期</span>
              </template>
            </el-table-column>
            <el-table-column label="使用时间" prop="useTime"/>
          <el-table-column label="操作" align="center" width="150">
            <template slot-scope="scope" >
              <el-button
                v-if="scope.row.useStatus == 0"
                size="mini"
                type="text"
                icon="el-icon-takeaway-box"
                @click="writeOff(scope.row)"
                v-hasPermi="['system:couponDraw:checkQrcode']"
              >核销
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="couponTotal>0"
          :total="couponTotal"
          :page.sync="couponQuery.pageNum"
          :limit.sync="couponQuery.pageSize"
          @pagination="getCouponList()"
        />
    </el-dialog>
    <!--查看优惠券详情-->
    <el-dialog title="优惠券详情信息" :visible.sync="openList" @close="cancelInfo" append-to-body>
      <el-table ref="table" :data="detailList">
        <el-table-column label="活动名称" prop="activityName">
          <template slot-scope="scope">
            <span>{{scope.row.isRelevancy? scope.row.activityName : "未绑定活动" }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="typeTitle" >
          <template slot-scope="scope">
            <span  v-if="scope.row.type == 0">{{scope.row.amount}}</span>
            <span  v-if="scope.row.type == 1">{{scope.row.discount}}折</span>
          </template>
        </el-table-column>
        <el-table-column label='领券上限' prop="collectionTimes"/>
        <el-table-column label="有效期开始日期" prop="startTime" width="180"/>
        <el-table-column label="有效期结束日期" prop="endTime" width="180"/>
        <el-table-column label="最低消费" align="center" prop="minCost" >
          <template slot-scope="scope">
            <span>{{scope.row.minCost == 0 ? '无限' : scope.row.minCost}}</span>
          </template>
        </el-table-column>
        <el-table-column label="使用须知" prop="useNotice"/>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>

import { downLoadExcel } from '@/utils/download'
import { list, getCoupon, addCoupon, editCoupon, delCoupon,getCouponList,modifiStatus,checkQrcode } from '@/api/coupon/list'
import upload from '@/components/ImageUpload'
import { listUser } from '@/api/merchant/merchant'
import { mapState } from 'vuex'

export default {
  name: 'couponList',
  components: { upload },

  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 优惠券表格数据
      roleList: [],
      // 弹出层标题
      title: '',
      //是否显示详情弹出层
      openlist: false,
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      // 有效日期日期范围（添加修改）
      dateRange: [],
      // 有效日期日期范围（筛选）
      dateRangeFilter: [],
      // 状态数据字典
      statusOptions: [ ],
      //优惠券详情列表
      detailList: [],
      //详情列表弹出框是否显示
      openList: false,
      // 数据范围选项
      dataScopeOptions: [
        {
          value: '1',
          label: '全部数据权限'
        },
        {
          value: '2',
          label: '自定数据权限'
        },
        {
          value: '3',
          label: '本部门数据权限'
        },
        {
          value: '4',
          label: '本部门及以下数据权限'
        },
        {
          value: '5',
          label: '仅本人数据权限'
        }
      ],
      pickerOptions: {
        shortcuts: [{
          text: '未来一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            end.setTime(end.getTime() + 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '未来一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            end.setTime(end.getTime() + 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '未来三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            end.setTime(end.getTime() + 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      // 菜单列表
      menuOptions: [],
      // 部门列表
      deptOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      // 表单参数
      form: {},
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      //优惠券状态
      couponStatus: [],
      //优惠券状态
      couponType: [],
      //商品类型
      couponGoodsType: [],
      //时间类型
      couponTimeType: [],
      //时间范围默认值
      timeValue:[],
      merchantOpen:false,
      //商户列表请求表单
      queryMerchant:{
        pageNum:1,
        pageSize:20
      },
      //商户列表数据
      merchantList:[],
      //商户列表总数
      merchantTotal:"",
      //数据详情表
      couponTable: [],
      //显示满减金额还是折扣金额的标题
      typeTitle:"折扣",
      //查看领券列表请求参数
      couponQuery:{
        pageNum:1,
        pageSize:10,
      },
      //领取列表总数
      couponTotal:0,
      // 表单校验
      rules: {
        title: [
          { required: true, message: '优惠券标题不能为空', trigger: 'blur' }
        ],
        amount: [
          { required: true, message: '减免金额不能为空', trigger: 'blur' }
        ],
        collectionTimes:[
          { required: true, message: '用户领券上限不能为空', trigger: 'blur' }
        ],
        minCost:[
          { required: true, message: '最低消费不能为空', trigger: 'blur' }
        ],
        status:[
          { required: true, message: '优惠券状态不能为空', trigger: 'blur' }
        ],
        type:[
          { required: true, message: '优惠券类型不能为空', trigger: 'blur' }
        ],
        goodsType:[
          { required: true, message: '商品类型不能为空', trigger: 'blur' }
        ],
        timeType:[
          { required: true, message: '商时间类型不能为空', trigger: 'blur' }
        ],
        days:[
          { required: true, message: '优惠券有效天数不能为空', trigger: 'blur' }
        ],
        startTime:[
          { required: true, message: '请选择时间范围', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '手机号码不能为空', trigger: 'blur' },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ],
      }
    }
  },
  created() {
    this.getList()
    this.getDicts('sys_normal_disable').then(response => {
      this.statusOptions = response.data;
      this.statusOptions.forEach(item =>{
        item.dictValue = Number(item.dictValue)

      })
    })
    //优惠券状态
    this.getDicts('coupon_status').then(response => {
      this.couponStatus = response.data;
      this.couponStatus.forEach(item =>{
        item.dictValue = Number(item.dictValue)
        if (item.dictValue == 2){
          item.disabled = true
        }

      })
      console.log(this.couponStatus)
    })
    //优惠券类型
    this.getDicts('coupon_type').then(response => {
      this.couponType = response.data;
      this.couponType.forEach(item =>{
        item.dictValue = Number(item.dictValue)

      })
    })
    //商品类型
    this.getDicts('coupon_ goodsType').then(response => {
      this.couponGoodsType = response.data;
      this.couponGoodsType.forEach(item =>{
        item.dictValue = Number(item.dictValue)
      })
    })
    //时间类型
    this.getDicts('coupon_timeType').then(response => {
      this.couponTimeType = response.data;
      this.couponTimeType.forEach(item =>{
        item.dictValue = Number(item.dictValue)
      })
    })
  },
  computed:{
    ...mapState({
      rolesKey:state => state.user.rolesKey
    }),
  },
  methods: {
    /** 查询优惠券列表 */
    getList() {
      this.loading = true
      list(this.queryParams).then(
        response => {
          this.roleList = response.rows
          this.total = response.total
          this.loading = false
        }
      )
    },
    //查询商户
    remoteMethod(e){
      this.queryMerchant.name = e
      this.getMerchantList()
    },
    //获取商户列表
    getMerchantList() {
      if (this.merchantOpen){
        this.loading = true;
      }
      listUser(this.queryMerchant).then(response => {
          this.merchantList = response.rows;
          this.merchantTotal = response.total;
          this.loading = false;
        }
      );
    },
    // 优惠券状态修改
    handleStatusChange(row) {
      let text = row.status === '0' ? '启用' : '停用'
      this.$confirm('确认要"' + text + '""' + row.roleName + '"优惠券吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return changeRoleStatus(row.roleId, row.status)
      }).then(() => {
        this.msgSuccess(text + '成功')
      }).catch(function() {
        row.status = row.status === '0' ? '1' : '0'
      })
    },
    //切换优惠券时间类型清除之前时间类型表单数据
    timeChange(e){
     if (e == 0){
       delete this.queryMerchant.startTime
       delete this.queryMerchant.endTime
     }
     if (e == 1){
       delete this.queryMerchant.days
     }
    },
    //有效时间日期选择器赋值（筛选）
    pickerChangeFilter(e){
      this.queryParams.startTime = e[0]
      this.queryParams.endTime = e[1]
    },
    //有效时间日期选择器赋值（添加/修改）
    pickerChange(e){
      this.form.startTime = e[0]
      this.form.endTime = e[1]
    },

    //核销
    writeOff(row){
      console.log(row)
      this.$confirm('是否核销用户'+row.userName+'的优惠券？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        checkQrcode({
          code:row.couponCode
        }).then(res=>{
          this.getCouponList()
          this.$message({
            type: 'success',
            message: '核销成功'
          });
        })
      }).catch(() => {

      });

    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    //查看详情取消按钮
    cancelInfo() {
      this.openList = false
      this.detailList = []
    },
    // 取消按钮（数据权限）
    cancelDataScope() {
      this.openDataScope = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {}
      this.resetForm('form');
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams={}
      this.dateRange = []
      this.resetForm('queryForm');
      // delete this.queryParams.shopId
      this.handleQuery()
    },
    //上传封面
    uploadSuccess(url) {
      this.form.coverImg = url
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      console.log(this.ids)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case 'handleDataScope':
          this.handleDataScope(row)
          break
        case 'handleAuthUser':
          this.handleAuthUser(row)
          break
        default:
          break
      }
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      if (type == 'menu') {
        let treeList = this.menuOptions
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value
        }
      } else if (type == 'dept') {
        let treeList = this.deptOptions
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value
        }
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type == 'menu') {
        this.$refs.menu.setCheckedNodes(value ? this.menuOptions : [])
      } else if (type == 'dept') {
        this.$refs.dept.setCheckedNodes(value ? this.deptOptions : [])
      }
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      if (type == 'menu') {
        this.form.menuCheckStrictly = value ? true : false
      } else if (type == 'dept') {
        this.form.deptCheckStrictly = value ? true : false
      }
    },
    //打开商户列表
    openMerchant(){
      this.getMerchantList();
      this.merchantOpen = true;
    },
    //重置商户传参数
    resetMerchantQuery(){
      this.resetForm('queryMerchantForm')
      this.getMerchantList()
    },
    //是否上架操作
    changePutStatus(val,row){
      modifiStatus({
        id:row.id,
        status:val
      }).then(res =>{
        if (res.code === 200){
          this.getList();
        }
      })
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.title = '添加优惠券';
      this.form = {
        shopId:row.id,
        status:0,
        goodsType:0,
        type:0,
        timeType:0
      }
      this.open = true;

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getCoupon(id).then(response => {
        this.form = response.data
        this.open = true
        this.timeValue = []
        this.timeValue.push(this.form.startTime)
        this.timeValue.push(this.form.endTime)
      if(response.data.status == 2){
        this.form.status = 1
      }
        this.title = '修改优惠券'
      })
    },
    /** 查询优惠券领取列表按钮操作 */
    handleGet(row) {
      this.couponTable=[];
      this.couponQuery.couponId = row.id;
      this.getCouponList()
    },
    /** 获取领券列表 */
    getCouponList(){
      this.loading = true
      getCouponList(this.couponQuery).then((response) => {
        this.couponTable = response.rows
        this.openlist = true;
        this.loading = false
        this.couponTotal = response.total
      }).catch(err=>{
        this.loading = false
      });
    },
    /**获取优惠券详情信息 */
    getDetail(row){
       this.detailList=[];
       const getid = row.id || this.ids;
       getCoupon(getid).then((response)=>{
         if(response.data.type == 0){
           this.typeTitle = "满减金额"
         }else if(response.data.type == 2){
           this.typeTitle = "兑换"
         }else {
           this.typeTitle = "折扣"
         }
         this.detailList.push(response.data)
         this.openList = true
       })
    },
    /** 选择优惠券权限范围触发 */
    dataScopeSelectChange(value) {
      if (value !== '2') {
        this.$refs.dept.setCheckedKeys([])
      }
    },
    /** 分配数据权限操作 */
    handleDataScope(row) {
      this.reset()
      const roleDeptTreeselect = this.getRoleDeptTreeselect(row.roleId)
      getRole(row.roleId).then(response => {
        this.form = response.data
        this.openDataScope = true
        this.$nextTick(() => {
          roleDeptTreeselect.then(res => {
            this.$refs.dept.setCheckedKeys(res.data.checkedKeys)
          })
        })
        this.title = '分配数据权限'
      })
    },
    /** 分配用户操作 */
    handleAuthUser: function(row) {
      const roleId = row.roleId
      this.$router.push('/system/role-auth/user/' + roleId)
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          //折扣变整数
          // if (this.form.discount || this.form.discount != null || this.form.discount != ""){
          //   this.form.discount = toString(this.form.discount)
          // }
          if (this.form.id != undefined) {
            editCoupon(this.form).then(response => {
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addCoupon(this.form).then(response => {
              this.msgSuccess('新增成功')
              this.open = false;
              this.merchantOpen = false;
              this.getList()
            })
          }
        }
      })
    },
    /** 提交按钮（数据权限） */
    submitDataScope: function() {
      if (this.form.roleId != undefined) {
        this.form.deptIds = this.getDeptAllCheckedKeys()
        dataScope(this.form).then(response => {
          this.msgSuccess('修改成功')
          this.openDataScope = false
          this.getList()
        })
      }
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const couponId = row.id || this.ids.toString()
      this.$confirm('是否确认删除优惠券为"' + couponId + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delCoupon(couponId)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      downLoadExcel('/shop/coupon/export', this.queryParams)
    }
  }
}
</script>
